package io.github.cargoshipping.infrastructure.persistence.hibernate;

import io.github.cargoshipping.domain.model.cargo.Cargo;
import io.github.cargoshipping.domain.model.cargo.CargoRepository;
import io.github.cargoshipping.domain.model.cargo.TrackingId;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.UUID;

/**
 * Hibernate implementation of CargoRepository.
 */
@Repository
public class CargoRepositoryHibernate extends HibernateRepository implements CargoRepository {

    @Override
    public Cargo find(TrackingId tid) {
        System.out.println("--------------------------------------- 根据 trackingId 查询 货物。");
        return (Cargo) getSession().
                createQuery("from Cargo where trackingId = :tid").
                setParameter("tid", tid).
                uniqueResult();
    }

    @Override
    public void store(Cargo cargo) {
        getSession().saveOrUpdate(cargo);
        // Delete-orphan does not seem to work correctly when the parent is a component
        getSession().createSQLQuery("delete from Leg where cargo_id = null").executeUpdate();
    }

    @Override
    public TrackingId nextTrackingId() {
        // TODO use an actual DB sequence here, UUID is for in-mem
        final String random = UUID.randomUUID().toString().toUpperCase();
        return new TrackingId(
                random.substring(0, random.indexOf("-"))
        );
    }

    @Override
    public List<Cargo> findAll() {
        return getSession().createQuery("from Cargo").list();
    }

}
